/**
 * 背诵模式管理
 * 三级评估：记住/模糊/不确定
 */

class RecitationManager {
    constructor() {
        this.words = [];
        this.currentIndex = 0;
        this.results = [];
        this.showingAnswer = false;
        this.sessionStartTime = null;
        
        console.log('📖 背诵管理器已加载');
    }

    /**
     * 开始背诵
     */
    start(words) {
        if (!words || words.length === 0) {
            alert('没有可用的单词');
            return;
        }

        this.words = this.sortByMastery(words);
        this.currentIndex = 0;
        this.results = [];
        this.sessionStartTime = Date.now();

        console.log(`开始背诵 ${this.words.length} 个单词`);
        this.render();
    }

    /**
     * 按掌握度排序
     */
    sortByMastery(words) {
        const recitationData = storageManager.get(storageManager.keys.RECITATION_DATA) || {};
        
        return [...words].sort((a, b) => {
            const scoreA = this.calculateMasteryScore(a.word, recitationData);
            const scoreB = this.calculateMasteryScore(b.word, recitationData);
            
            // 分数越低，越靠前（优先复习）
            if (scoreA !== scoreB) {
                return scoreA - scoreB;
            }
            
            // 同分数情况下，最近标记"不确定"的优先
            const lastUncertainA = this.getLastUncertainTime(a.word, recitationData);
            const lastUncertainB = this.getLastUncertainTime(b.word, recitationData);
            
            return lastUncertainB - lastUncertainA;
        });
    }

    /**
     * 计算掌握度分数
     */
    calculateMasteryScore(word, recitationData) {
        const data = recitationData[word];
        if (!data || data.total === 0) {
            return 0; // 未学习的单词优先
        }
        
        return (data.remember * 2 + data.vague * 1) / (data.total * 2) * 100;
    }

    /**
     * 获取最后一次标记"不确定"的时间
     */
    getLastUncertainTime(word, recitationData) {
        const data = recitationData[word];
        if (!data || !data.history) {
            return 0;
        }
        
        const uncertainRecords = data.history.filter(h => h.status === 'uncertain');
        if (uncertainRecords.length === 0) {
            return 0;
        }
        
        return new Date(uncertainRecords[uncertainRecords.length - 1].date).getTime();
    }

    /**
     * 渲染背诵界面
     */
    render() {
        const container = document.querySelector('.recitation-container');
        if (!container) return;

        const currentWord = this.words[this.currentIndex];
        this.showingAnswer = false;

        // 更新进度信息
        this.updateProgress();

        // 渲染单词卡片 - 横屏优化布局
        container.innerHTML = `
            <div class="recitation-card-wide animate-fadeIn">
                <div class="recitation-left">
                    <div class="word-number">第 ${this.currentIndex + 1} 个单词</div>
                    
                    <div class="word-display-large">
                        <h2 class="word-text-large">${this.formatWordDisplay(currentWord.word)}</h2>
                    </div>

                    <div class="word-actions">
                        <button class="btn-play-large" id="btn-play-word" title="播放发音">
                            <svg viewBox="0 0 24 24" width="40" height="40">
                                <path fill="currentColor" d="M8 5v14l11-7z"/>
                            </svg>
                            <span>播放发音</span>
                        </button>
                    </div>

                    <div class="word-meta">
                        ${currentWord.category ? `<div class="meta-item">🏷️ ${currentWord.category}</div>` : ''}
                        ${currentWord.type ? `<div class="meta-item">📝 ${currentWord.type}</div>` : ''}
                    </div>
                </div>

                <div class="recitation-right">
                    <div class="answer-area-wide" id="answer-area">
                        <div class="answer-placeholder">
                            <div class="placeholder-icon">💭</div>
                            <button class="btn btn-primary btn-extra-large" id="btn-show-answer">
                                点击查看中文释义
                            </button>
                            <p class="hint-text">💡 先思考中文意思，再点击查看</p>
                        </div>
                    </div>

                    <div class="bottom-actions">
                        <button class="btn btn-secondary" id="btn-skip">⏭️ 跳过</button>
                    </div>
                </div>
            </div>
        `;

        this.bindEvents();
        
        // 自动播放一次单词 🆕
        setTimeout(() => {
            this.playWord();
        }, 300);
    }

    /**
     * 格式化单词显示
     */
    formatWordDisplay(word) {
        // 如果是驼峰短语，特殊处理显示
        if (word.includes(' ')) {
            // 转换为驼峰格式显示
            const words = word.split(' ');
            const camelCase = words[0].toLowerCase() + 
                            words.slice(1).map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join('');
            return camelCase;
        }
        return word;
    }

    /**
     * 显示答案
     */
    showAnswer() {
        if (this.showingAnswer) return;

        const currentWord = this.words[this.currentIndex];
        const answerArea = document.getElementById('answer-area');
        
        if (!answerArea) return;

        this.showingAnswer = true;

        // 渲染答案和详细信息 - 横屏布局
        answerArea.innerHTML = `
            <div class="answer-content-wide animate-fadeIn">
                <div class="answer-main">
                    <div class="answer-translation-large">
                        <h3>${currentWord.translation || '(无释义)'}</h3>
                    </div>

                    <div class="word-details">
                        ${currentWord.type ? `
                            <div class="word-info-wide">
                                <span class="info-label">📝 类型:</span>
                                <span class="info-value">${currentWord.type === '驼峰短语' ? '方法名 · camelCase' : currentWord.type}</span>
                            </div>
                        ` : ''}

                        ${currentWord.category ? `
                            <div class="word-info-wide">
                                <span class="info-label">🏷️ 分类:</span>
                                <span class="info-value">${currentWord.category}</span>
                            </div>
                        ` : ''}

                        ${currentWord.languages ? `
                            <div class="word-info-wide">
                                <span class="info-label">💻 语言:</span>
                                <span class="info-value">${currentWord.languages}</span>
                            </div>
                        ` : ''}
                    </div>

                    ${currentWord.example_code ? `
                        <div class="word-example-wide">
                            <div class="example-label">💻 代码示例:</div>
                            <code class="example-code">${this.escapeHtml(currentWord.example_code)}</code>
                        </div>
                    ` : ''}
                </div>

                <div class="assessment-section-wide">
                    <p class="assessment-question">掌握程度如何？</p>
                    <div class="assessment-buttons-wide">
                        <button class="btn-assessment-wide btn-remember" data-status="remember">
                            <span class="assessment-icon-large">✅</span>
                            <span class="assessment-text-large">记住</span>
                            <span class="assessment-desc">完全掌握</span>
                        </button>
                        <button class="btn-assessment-wide btn-vague" data-status="vague">
                            <span class="assessment-icon-large">🤔</span>
                            <span class="assessment-text-large">模糊</span>
                            <span class="assessment-desc">似曾相识</span>
                        </button>
                        <button class="btn-assessment-wide btn-uncertain" data-status="uncertain">
                            <span class="assessment-icon-large">❌</span>
                            <span class="assessment-text-large">不确定</span>
                            <span class="assessment-desc">完全不会</span>
                        </button>
                    </div>
                    <p class="keyboard-hint">快捷键: 1-记住 / 2-模糊 / 3-不确定</p>
                </div>
            </div>
        `;

        // 绑定评估按钮
        const assessmentBtns = document.querySelectorAll('.btn-assessment, .btn-assessment-wide');
        assessmentBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                const status = btn.dataset.status;
                this.recordAssessment(status);
            });
        });
    }

    /**
     * 转义HTML
     */
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        // 播放发音按钮
        const playBtn = document.getElementById('btn-play-word');
        if (playBtn) {
            playBtn.addEventListener('click', () => {
                this.playWord();
            });
        }

        // 显示答案按钮
        const showAnswerBtn = document.getElementById('btn-show-answer');
        if (showAnswerBtn) {
            showAnswerBtn.addEventListener('click', () => {
                this.showAnswer();
            });
        }

        // 跳过按钮
        const skipBtn = document.getElementById('btn-skip');
        if (skipBtn) {
            skipBtn.addEventListener('click', () => {
                this.skip();
            });
        }

        // 键盘快捷键
        this.setupKeyboard();
    }

    /**
     * 设置键盘快捷键
     */
    setupKeyboard() {
        const handleKey = (e) => {
            // 如果在输入框中，不处理
            if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
                return;
            }

            switch(e.key) {
                case ' ':
                case 'Space':
                    e.preventDefault();
                    if (!this.showingAnswer) {
                        this.showAnswer();
                    } else {
                        this.playWord();
                    }
                    break;
                case '1':
                    if (this.showingAnswer) {
                        this.recordAssessment('remember');
                    }
                    break;
                case '2':
                    if (this.showingAnswer) {
                        this.recordAssessment('vague');
                    }
                    break;
                case '3':
                    if (this.showingAnswer) {
                        this.recordAssessment('uncertain');
                    }
                    break;
                case 'Escape':
                    this.exit();
                    break;
            }
        };

        // 移除旧的监听器（如果有）
        if (this.keyboardHandler) {
            document.removeEventListener('keydown', this.keyboardHandler);
        }
        
        this.keyboardHandler = handleKey;
        document.addEventListener('keydown', handleKey);
    }

    /**
     * 播放单词发音
     */
    playWord() {
        const currentWord = this.words[this.currentIndex];
        if (!currentWord) return;

        if (window.speechManager) {
            const word = currentWord.word;
            
            // 判断是否是驼峰短语
            if (currentWord.type === '驼峰短语' || currentWord.pronunciation_mode === 'split') {
                speechManager.speakCamelCase(this.formatWordDisplay(word));
            } else {
                speechManager.speak(word);
            }
        }
    }

    /**
     * 跳过当前单词
     */
    skip() {
        // 跳过不记录评估
        this.next();
    }

    /**
     * 记录评估
     */
    recordAssessment(status) {
        const currentWord = this.words[this.currentIndex];
        
        // 保存结果
        this.results.push({
            word: currentWord.word,
            translation: currentWord.translation,
            status: status,
            timestamp: Date.now()
        });

        // 保存到存储
        this.saveToStorage(currentWord.word, status);

        // 下一个
        this.next();
    }

    /**
     * 保存到存储
     */
    saveToStorage(word, status) {
        const recitationData = storageManager.get(storageManager.keys.RECITATION_DATA) || {};
        
        if (!recitationData[word]) {
            recitationData[word] = {
                remember: 0,
                vague: 0,
                uncertain: 0,
                total: 0,
                masteryScore: 0,
                lastRecitation: null,
                lastStatus: null,
                history: []
            };
        }

        const data = recitationData[word];
        data.total++;
        data[status]++;
        data.lastRecitation = new Date().toISOString();
        data.lastStatus = status;
        
        // 计算掌握度分数
        data.masteryScore = (data.remember * 2 + data.vague * 1) / (data.total * 2) * 100;

        // 记录历史
        data.history.push({
            date: new Date().toISOString(),
            status: status
        });

        storageManager.set(storageManager.keys.RECITATION_DATA, recitationData);

        console.log(`记录评估: ${word} - ${status}`);
    }

    /**
     * 下一个
     */
    next() {
        this.currentIndex++;
        if (this.currentIndex < this.words.length) {
            this.render();
        } else {
            this.finish();
        }
    }

    /**
     * 更新进度信息
     */
    updateProgress() {
        document.getElementById('recitation-current').textContent = this.currentIndex + 1;
        document.getElementById('recitation-total').textContent = this.words.length;
        
        // 计算已掌握数量
        const masteredCount = this.results.filter(r => r.status === 'remember').length;
        document.getElementById('recitation-mastered').textContent = masteredCount;
    }

    /**
     * 完成背诵
     */
    finish() {
        console.log('背诵完成', this.results);
        
        // 移除键盘监听
        if (this.keyboardHandler) {
            document.removeEventListener('keydown', this.keyboardHandler);
            this.keyboardHandler = null;
        }

        // 计算统计数据
        const stats = this.calculateStats();

        // 保存会话记录
        this.saveSession(stats);

        // 显示结果页面
        this.renderResults(stats);
    }

    /**
     * 计算统计数据
     */
    calculateStats() {
        const total = this.results.length;
        const remember = this.results.filter(r => r.status === 'remember').length;
        const vague = this.results.filter(r => r.status === 'vague').length;
        const uncertain = this.results.filter(r => r.status === 'uncertain').length;
        
        const rememberPercent = total > 0 ? Math.round((remember / total) * 100) : 0;
        const vaguePercent = total > 0 ? Math.round((vague / total) * 100) : 0;
        const uncertainPercent = total > 0 ? Math.round((uncertain / total) * 100) : 0;

        return {
            total,
            remember,
            vague,
            uncertain,
            rememberPercent,
            vaguePercent,
            uncertainPercent,
            duration: Date.now() - this.sessionStartTime
        };
    }

    /**
     * 保存会话记录
     */
    saveSession(stats) {
        const sessions = storageManager.get(storageManager.keys.SESSIONS) || [];
        
        // 提取单词本ID
        const wordbookIds = [...new Set(this.words.map(w => w.wordbookId).filter(id => id))];
        
        const session = {
            sessionId: `recitation-${Date.now()}`,
            mode: 'recitation',
            startTime: new Date(this.sessionStartTime).toISOString(),
            endTime: new Date().toISOString(),
            duration: stats.duration,
            totalWords: stats.total,
            remember: stats.remember,
            vague: stats.vague,
            uncertain: stats.uncertain,
            wordbookIds: wordbookIds,
            results: this.results
        };

        sessions.push(session);
        storageManager.set(storageManager.keys.SESSIONS, sessions);

        console.log('会话已保存');

        // 更新相关单词本的统计数据
        if (window.wordbookManager) {
            wordbookIds.forEach(id => {
                wordbookManager.updateWordbookStats(id);
            });
        }
    }

    /**
     * 渲染结果页面
     */
    renderResults(stats) {
        const container = document.querySelector('.recitation-container');
        if (!container) return;

        const duration = Math.floor(stats.duration / 1000);
        const minutes = Math.floor(duration / 60);
        const seconds = duration % 60;

        // 获取需要重点复习的单词
        const needReview = this.results.filter(r => 
            r.status === 'uncertain' || r.status === 'vague'
        );

        container.innerHTML = `
            <div class="results-container animate-fadeIn">
                <div class="results-header">
                    <h2>🎉 背诵完成！</h2>
                </div>

                <div class="results-summary">
                    <div class="summary-card">
                        <div class="summary-label">总计</div>
                        <div class="summary-value">${stats.total}</div>
                    </div>
                    <div class="summary-card card-success">
                        <div class="summary-label">✅ 记住</div>
                        <div class="summary-value">${stats.remember}</div>
                        <div class="summary-percent">${stats.rememberPercent}%</div>
                    </div>
                    <div class="summary-card card-warning">
                        <div class="summary-label">🤔 模糊</div>
                        <div class="summary-value">${stats.vague}</div>
                        <div class="summary-percent">${stats.vaguePercent}%</div>
                    </div>
                    <div class="summary-card card-error">
                        <div class="summary-label">❌ 不确定</div>
                        <div class="summary-value">${stats.uncertain}</div>
                        <div class="summary-percent">${stats.uncertainPercent}%</div>
                    </div>
                </div>

                <div class="results-meta">
                    <span>⏱️ 用时: ${minutes}分${seconds}秒</span>
                    <span>📅 完成时间: ${new Date().toLocaleTimeString()}</span>
                </div>

                ${needReview.length > 0 ? `
                    <div class="review-section">
                        <h3>📕 需要重点复习的单词</h3>
                        <div class="review-words">
                            ${needReview.map(r => `
                                <div class="review-word-item">
                                    <span class="review-word">${this.formatWordDisplay(r.word)}</span>
                                    <span class="review-translation">${r.translation}</span>
                                    <span class="review-status ${r.status === 'uncertain' ? 'status-uncertain' : 'status-vague'}">
                                        ${r.status === 'uncertain' ? '不确定' : '模糊'}
                                    </span>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                ` : `
                    <div class="perfect-message">
                        <div class="perfect-icon">🌟</div>
                        <h3>完美！所有单词都已掌握</h3>
                    </div>
                `}

                <div class="results-actions">
                    ${needReview.length > 0 ? `
                        <button class="btn btn-primary" id="btn-review-again">
                            继续复习不熟的词 (${needReview.length}个)
                        </button>
                    ` : ''}
                    <button class="btn btn-secondary" id="btn-back-home">返回首页</button>
                </div>
            </div>
        `;

        // 绑定按钮事件
        const reviewBtn = document.getElementById('btn-review-again');
        if (reviewBtn) {
            reviewBtn.addEventListener('click', () => {
                // 重新开始，只背诵不熟的词
                const reviewWords = needReview.map(r => {
                    return this.words.find(w => w.word === r.word);
                }).filter(w => w);
                
                this.start(reviewWords);
            });
        }

        const backBtn = document.getElementById('btn-back-home');
        if (backBtn) {
            backBtn.addEventListener('click', () => {
                if (window.app) {
                    app.navigateTo('home');
                    // 刷新首页，更新进度
                    setTimeout(() => {
                        app.updateHomePage();
                    }, 100);
                }
            });
        }
    }

    /**
     * 退出背诵模式
     */
    exit() {
        if (confirm('确定要退出吗？当前进度将不会保存。')) {
            // 移除键盘监听
            if (this.keyboardHandler) {
                document.removeEventListener('keydown', this.keyboardHandler);
                this.keyboardHandler = null;
            }
            
            if (window.app) {
                app.navigateTo('home');
            }
        }
    }
}

// 全局实例
const recitationManager = new RecitationManager();
window.recitationManager = recitationManager;
